package com.jushu.storbox.view.resolve;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;

import com.jushu.storbox.R;
import com.jushu.storbox.actions.ActionShare;
import com.jushu.storbox.actions.FolderAction;
import com.jushu.storbox.adapter.FileDisplayAdapter;
import com.jushu.storbox.callback.FileFolderInfoFileSizeSort;
import com.jushu.storbox.callback.FileFolderInfoNameSort;
import com.jushu.storbox.callback.FileFolderInfoTimeSort;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.newfragment.argument.FileActionArgs;
import com.jushu.storbox.operation.group.FileItemMoreOperation;
import com.jushu.storbox.operation.group.OtherPersonShareFileOperation;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.view.dialog.PopupMenuWindow;
import com.jushu.storbox.vo.PagedList;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.util.StringUtil;
import com.kennyc.view.MultiStateView;

public abstract class OtherPersonShareFilleDisplayResolve 
		extends ListDisplayResolve<FileFolderInfo, 
								FileItemMoreOperation<FileFolderInfo>, 
								FileDisplayAdapter>
		implements OtherPersonShareFileOperation<FileFolderInfo>{
	
	protected final static String TAG = OtherPersonShareFilleDisplayResolve.class.getSimpleName();
	
	private Stack<FileActionArgs> folderStack = new Stack<FileActionArgs>();
	private List<FileFolderInfo> datas = new ArrayList<FileFolderInfo>();
	private String clickedItemOwnerId=null;
	private MultiStateView multiStateView;
	
	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			loadDataList();
		}
	};
	
	OtherPersonShareFileOperationImpl operation = new OtherPersonShareFileOperationImpl();
	
	public OtherPersonShareFilleDisplayResolve(Activity activity, FileActionArgs folderArgument) {
		super(activity);
	}
	
	public OtherPersonShareFilleDisplayResolve(Activity activity, FileActionArgs folderArgument, MultiStateView multiStateView) {
		super(activity);
		this.multiStateView = multiStateView;
		multiStateView.getView(MultiStateView.ViewState.ERROR).findViewById(R.id.button1).setOnClickListener(listener);
	}
	
	@Override
	protected FileDisplayAdapter initTemplateAdapter() {
		adapter = new FileDisplayAdapter(getActivity(), datas);
		adapter.setPopWindow(operation.popWindow);
		return adapter;
	}
	
	@Override
	protected FileItemMoreOperation<FileFolderInfo> initAdapterOperation() {
		return operation;
	}

	//setting and getting
	private Activity getActivity() {
		return (Activity) context;
	}
	
	public Stack<FileActionArgs> getFolderStack() {
		return folderStack;
	}
	
	@Override
	protected void clickItem(View clickView, int position, long id,
			FileFolderInfo info) {
		clickedItemOwnerId = info.getOwnerId();
		if(FileType.File.value() == info.getIsFile()) {
			openFile(position, info);
		} else {
			openFolder(position, info);
		}
	}

	private void openFile(int index, FileFolderInfo info) {
		new ActionShare().openOthersShare(context, info, msgHandler);
	}
	private void openFolder(int index, FileFolderInfo info) {
		new FolderAction().openFolder(context, MessageCode.OPEN_FOLDER, 
				info.getOwnerId(), info.getId(), info.getName(), Constant.FIRST_PAGE_INDEX, msgHandler);
	}
	
	public void openParentFolder() {
		if(!folderStack.isEmpty()) {
			folderStack.pop();
		}
		if(!folderStack.isEmpty()) {
			FileActionArgs parentArgument = folderStack.peek();
			clickedItemOwnerId = getOpendResourceOwnerId();
			if(StringUtil.isNotBlank(clickedItemOwnerId)) {
				new FolderAction().openFolder(context, MessageCode.OPEN_PARENT_FOLDER, 
					clickedItemOwnerId, parentArgument.getFolderId(), parentArgument.getFolderName(), Constant.FIRST_PAGE_INDEX, msgHandler);
			} else {
				LogUtil.e(TAG, "ownerId is null");
			}
		} else {
			handleNoMoreParent();
		}
	}
	public void getMoreDataList() {
		FileActionArgs folderArgument = folderStack.peek();
		if(folderArgument.getKeyWords() == null){
			clickedItemOwnerId = getOpendResourceOwnerId();
			if(StringUtil.isNotBlank(clickedItemOwnerId)) {
				new FolderAction().getMoreNodeListFromServer(context, clickedItemOwnerId, folderArgument.getFolderId(), folderArgument.getPageIndex(), msgHandler);
			} else {
				LogUtil.e(TAG, "ownerId is null");
			}
		}
	}
	
	@Override
	protected void refreshDataList() {
		if(!folderStack.isEmpty()) {
			FileActionArgs folderArgument = folderStack.peek();
			if(folderArgument.getKeyWords() == null){
				folderArgument.setPageIndex(Constant.FIRST_PAGE_INDEX);
				clickedItemOwnerId = getOpendResourceOwnerId();
				if(StringUtil.isNotBlank(clickedItemOwnerId)) {
					new FolderAction().openFolder(context, MessageCode.LOAD_FILE_LIST, 
							clickedItemOwnerId, folderArgument.getFolderId(), folderArgument.getFolderName(), Constant.FIRST_PAGE_INDEX, msgHandler);
				} else {
					LogUtil.e(TAG, "ownerId is null");
				}
			}
		} else {
			LogUtil.e(TAG,"some error occured!");
		}
	}

	protected void handleNoMoreParent() {
	}

	protected abstract String aqureOpendResourceOwnerId();
	private String getOpendResourceOwnerId() {
		if(StringUtil.isBlank(clickedItemOwnerId)) {
			clickedItemOwnerId = aqureOpendResourceOwnerId();
		}
		return clickedItemOwnerId;
	}
	
	@Override
	public void binddingAdapter() {
		clickedItemOwnerId = null;
		super.binddingAdapter();
	}
	
	@Override
	public void onSaveItem(int index, FileFolderInfo info) {
	}
	
	public void binddingPagedList(PagedList<FileFolderInfo> pageList) {
		folderStack.clear();
		FileActionArgs newFolder = new FileActionArgs();
		newFolder.setFolderId(pageList.getPagedFolderId());
		newFolder.setFolderName(pageList.getPagedFolderName());
		newFolder.setPageIndex(Constant.FIRST_PAGE_INDEX);
		folderStack.push(newFolder);
		resetDatas(pageList.getPagedList());
	}
	
	protected void updateCurrentFolder(String ownerId, String folderId, String folderName) {
	}
	
	ClientExceptionRelateHandler msgHandler = new ClientExceptionRelateHandler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			if (msg.obj instanceof ClientException && null != multiStateView) {
				multiStateView.setViewState(MultiStateView.ViewState.CONTENT);
			} else if (null != multiStateView) {
				multiStateView.setViewState(MultiStateView.ViewState.CONTENT);
			}
			switch(msg.what) {
			case MessageCode.LOAD_FILE_LIST:
				PagedList<FileFolderInfo> pagedList = (PagedList<FileFolderInfo>) msg.obj;
				handlerLoadFileList(msg, folderStack.peek(), pagedList);
				break;
			case MessageCode.OPEN_FOLDER:
				PagedList<FileFolderInfo> res = (PagedList<FileFolderInfo>)msg.obj;
				folderStack.push(new FileActionArgs());
				FileActionArgs newFolder = folderStack.peek();
				newFolder.setFolderId(res.getPagedFolderId());
				newFolder.setFolderName(res.getPagedFolderName());
				newFolder.setPageIndex(Constant.FIRST_PAGE_INDEX);
				updateCurrentFolder(clickedItemOwnerId, newFolder.getFolderId(), newFolder.getFolderName());
				handlerLoadFileList(msg, newFolder, res);
				break;
			case MessageCode.OPEN_PARENT_FOLDER:
				PagedList<FileFolderInfo> tmpRes = (PagedList<FileFolderInfo>)msg.obj;
				if(!folderStack.isEmpty()) {
					FileActionArgs parentFolder = folderStack.peek();
					parentFolder.setFolderId(tmpRes.getPagedFolderId());
					parentFolder.setFolderName(tmpRes.getPagedFolderName());
					parentFolder.setPageIndex(Constant.FIRST_PAGE_INDEX);
					updateCurrentFolder(clickedItemOwnerId, parentFolder.getFolderId(), parentFolder.getFolderName());
					handlerLoadFileList(msg, parentFolder, tmpRes);
				}
				break;
			 default:
				 super.handleMessage(msg);
			}
		}

		private void handlerLoadFileList(Message msg, FileActionArgs folderArg, PagedList<FileFolderInfo> pagedList) {
			List<FileFolderInfo> pagedData = pagedList.getPagedList();
			onRefreshComplete();
			if(folderArg.getPageIndex() == Constant.FIRST_PAGE_INDEX){
				adapter.cleanListDatasOnly();
			}
			if(pagedData != null){
				adapter.addDatas(pagedData);
				if(pagedList.getTotal() == ClientConfig.CLOUD_COUNT_PER_PAGE) {
					folderArg.incPageIndex();
				}
			}
		}
		
		@Override
		protected void onHandlerBefore(Message msg, String errorCode) {
			onRefreshComplete();
			super.onHandlerBefore(msg, errorCode);
		}
		@Override
		public Context getContext() {
			return getActivity();
		}
	};

	//node operation
	class OtherPersonShareFileOperationImpl implements FileItemMoreOperation<FileFolderInfo>{
		
		public PopupMenuWindow popWindow;
		private int mIndex;
		private FileFolderInfo mInfo;
		
		public OtherPersonShareFileOperationImpl() {
			popWindow = new PopupMenuWindow(context, 
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 
					R.layout.adapter_friends_shareview_item_window_more) {
				@Override
				protected void onInflaterFinished(View contentView) {
					super.onInflaterFinished(contentView);
					View saveAction = contentView.findViewById(R.id.adapter_view_shareitem_window_more_save);
					saveAction.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							LogUtil.i(TAG, "save: "+mIndex);
							dismiss();
							onSaveItem(mIndex, mInfo);
						}
					});
				}
			};
		}
		
		@Override
		public void onItemMore(int index, FileFolderInfo info) {
			mIndex = index;
			mInfo = info;
		}	
	};

	public void shareSubSortByFileName(int sortType, String currentRoot){
		adapter.sort(new FileFolderInfoNameSort(sortType));
		if(currentRoot.equals(UiConstant.SHARE_RECIVE_SUB_CURRENT_SORT)){
			writePreferenceForSort(UiConstant.SHARE_RECIVE_SUB_FILENAME_SORT, sortType, currentRoot);
		}else{
			writePreferenceForSort(UiConstant.SHARE_SEND_SUB_FILENAME_SORT, sortType, currentRoot);
		}
		
		
	}
	
	public void shareSubSortBySize(int sortType, String currentRoot){
		adapter.sort(new FileFolderInfoFileSizeSort(sortType));
		if(currentRoot.equals(UiConstant.SHARE_RECIVE_SUB_CURRENT_SORT)){
			writePreferenceForSort(UiConstant.SHARE_RECIVE_SUB_SIZE_SORT, sortType, currentRoot);
		}else{
			writePreferenceForSort(UiConstant.SHARE_SEND_SUB_SIZE_SORT, sortType, currentRoot);
		}
	}
	
	public void shareSubSortByTime(int sortType, String currentRoot){
		adapter.sort(new FileFolderInfoTimeSort(sortType));
		if(currentRoot.equals(UiConstant.SHARE_RECIVE_SUB_CURRENT_SORT)){
			writePreferenceForSort(UiConstant.SHARE_RECIVE_SUB_TIME_SORT, sortType, currentRoot);
		}else{
			writePreferenceForSort(UiConstant.SHARE_SEND_SUB_TIME_SORT, sortType, currentRoot);
		}
		
	}
	
	void writePreferenceForSort(String str, int sortType, String currentRoot){
		SharedPreferences preference = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
		Editor edit = preference.edit();
			edit.putInt(str, sortType);
			edit.putInt(currentRoot, sortType);
			
//		if(str.equals(UiConstant.SHARE_RECIVE_SUB_FILENAME_SORT)){
//			edit.putInt(UiConstant.SHARE_RECIVE_SUB_FILENAME_SORT, sortType);
//			edit.putInt(UiConstant.SHARE_RECIVE_SUB_CURRENT_SORT, sortType);
//		}
//		if(str.equals(UiConstant.SHARE_RECIVE_SUB_SIZE_SORT)){
//			edit.putInt(UiConstant.SHARE_RECIVE_SUB_SIZE_SORT, sortType);
//			edit.putInt(UiConstant.SHARE_RECIVE_SUB_CURRENT_SORT, sortType);
//		}
//		if(str.equals(UiConstant.SHARE_RECIVE_SUB_TIME_SORT)){
//			edit.putInt(UiConstant.SHARE_RECIVE_SUB_TIME_SORT, sortType);
//			edit.putInt(UiConstant.SHARE_RECIVE_SUB_CURRENT_SORT, sortType);
//		}
			edit.commit();
	}

}
